package com.corgi.encrypt.advice;

import com.alibaba.fastjson.JSON;
import com.corgi.encrypt.RSAUtil;
import com.corgi.encrypt.annotation.Encrypt;
import com.corgi.encrypt.properties.EncryptProperties;
import com.corgi.encrypt.util.Base64Util;
import com.corgi.encrypt.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @title: EncryptResponseBodyAdvice
 * @description:
 * @author: dengmiao
 * @create: 2019-10-23 15:22
 **/
@Slf4j
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private boolean encrypt;

    @Autowired
    private EncryptProperties encryptProperties;

    private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getMethod().isAnnotationPresent(Encrypt.class) && encryptProperties.isOpen()) {
            encrypt = true;
        }
        return encrypt;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Boolean status = encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
            return o;
        }
        if (encrypt) {
            String publicKey = encryptProperties.getPublicKey();
            try {
                String content = JSON.toJSONString(o);
                if (!StringUtils.hasText(publicKey)) {
                    throw new NullPointerException("Please configure rsa.encrypt.private key parameter!");
                }
                byte[] data = content.getBytes();
                byte[] encodedData = RsaUtil.encrypt(data, publicKey);
                String result = Base64Util.encode(encodedData);
                result = RSAUtil.publicEncrypt(content, publicKey);
                if(encryptProperties.isShowLog()) {
                    log.info("Pre-encrypted data：{}，After encryption：{}", content, result);
                }
                return result;
            } catch (Exception e) {
                log.error("Encrypted data exception", e);
            }
        }
        return o;
    }
}
